#!/usr/bin/env node

/**
 * Shopify应用配置验证脚本
 * 用于验证所有必需的环境变量和配置是否正确设置
 */

import { config } from 'dotenv';
import { readFileSync } from 'fs';
import { join } from 'path';

// 加载环境变量 - 从父目录的.env文件
config({ path: '../.env' });

console.log('🔍 开始验证Shopify应用配置...\n');

let hasErrors = false;

/**
 * 验证环境变量
 */
function checkEnvVar(name, value, required = true) {
  if (!value && required) {
    console.log(`❌ 缺少必需的环境变量: ${name}`);
    hasErrors = true;
    return false;
  } else if (value) {
    console.log(`✅ ${name}: ${value.substring(0, 8)}${'*'.repeat(Math.max(0, value.length - 8))}`);
    return true;
  } else {
    console.log(`⚠️  可选环境变量未设置: ${name}`);
    return true;
  }
}

/**
 * 验证URL格式
 */
function validateUrl(url, name) {
  try {
    new URL(url);
    console.log(`✅ ${name} URL格式正确: ${url}`);
    return true;
  } catch (error) {
    console.log(`❌ ${name} URL格式错误: ${url}`);
    hasErrors = true;
    return false;
  }
}

console.log('📋 检查必需的环境变量:');
console.log('=====================================');

// 检查必需的环境变量
checkEnvVar('SHOPIFY_API_KEY', process.env.SHOPIFY_API_KEY);
checkEnvVar('SHOPIFY_API_SECRET', process.env.SHOPIFY_API_SECRET);
checkEnvVar('HOST', process.env.HOST);

console.log('\n📋 检查可选的环境变量:');
console.log('=====================================');

// 检查可选的环境变量
checkEnvVar('SHOPIFY_SCOPES', process.env.SHOPIFY_SCOPES, false);
checkEnvVar('SHOPIFY_API_VERSION', process.env.SHOPIFY_API_VERSION, false);
checkEnvVar('SHOPIFY_WEBHOOK_SECRET', process.env.SHOPIFY_WEBHOOK_SECRET, false);
checkEnvVar('PORT', process.env.PORT, false);
checkEnvVar('NODE_ENV', process.env.NODE_ENV, false);

console.log('\n🔗 验证URL配置:');
console.log('=====================================');

// 验证URL配置
if (process.env.HOST) {
  const host = process.env.HOST;
  const appUrl = `https://${host}`;
  const callbackUrl = `https://${host}/api/auth/callback`;
  
  validateUrl(appUrl, '应用URL');
  validateUrl(callbackUrl, '回调URL');
  
  console.log('\n📝 Shopify Partners Dashboard 配置提醒:');
  console.log('=====================================');
  console.log(`App URL: ${appUrl}`);
  console.log(`Allowed redirection URL: ${callbackUrl}`);
}

console.log('\n🔧 检查配置文件:');
console.log('=====================================');

// 检查配置文件
try {
  const tomlContent = readFileSync('../shopify.app.toml', 'utf8');
  if (tomlContent.includes('read_products,write_products')) {
    console.log('✅ shopify.app.toml 权限范围已更新');
  } else {
    console.log('⚠️  shopify.app.toml 可能需要更新权限范围');
  }
} catch (error) {
  console.log('❌ 无法读取 shopify.app.toml 文件');
  hasErrors = true;
}

// 检查Shopify配置文件
try {
  const configExists = readFileSync('shopify.js', 'utf8');
  if (configExists.includes('SHOPIFY_API_KEY')) {
    console.log('✅ shopify.js 配置已更新');
  } else {
    console.log('❌ shopify.js 配置可能不完整');
    hasErrors = true;
  }
} catch (error) {
  console.log('❌ 无法读取 shopify.js 文件');
  hasErrors = true;
}

console.log('\n🏗️ 检查项目依赖:');
console.log('=====================================');

// 检查关键依赖
try {
  const packageJson = JSON.parse(readFileSync('package.json', 'utf8'));
  const requiredDeps = [
    '@shopify/shopify-app-express',
    '@shopify/shopify-app-session-storage-sqlite',
    'dotenv'
  ];
  
  requiredDeps.forEach(dep => {
    if (packageJson.dependencies && packageJson.dependencies[dep]) {
      console.log(`✅ 依赖已安装: ${dep}`);
    } else {
      console.log(`❌ 缺少依赖: ${dep}`);
      hasErrors = true;
    }
  });
} catch (error) {
  console.log('❌ 无法读取 package.json 文件');
  hasErrors = true;
}

console.log('\n🎯 配置验证结果:');
console.log('=====================================');

if (hasErrors) {
  console.log('❌ 配置验证失败！请修复上述错误后重试。');
  console.log('\n💡 建议操作:');
  console.log('1. 检查 .env 文件是否存在并包含所有必需变量');
  console.log('2. 确认 Shopify Partners Dashboard 配置正确');
  console.log('3. 运行 npm install 安装依赖');
  console.log('4. 参考 ENVIRONMENT_SETUP.md 和 SHOPIFY_CONFIG_NOTES.md');
  
  process.exit(1);
} else {
  console.log('✅ 配置验证成功！应用已准备就绪。');
  console.log('\n🚀 下一步操作:');
  console.log('1. 运行 npm run dev 启动开发服务器');
  console.log('2. 访问应用URL开始安装流程');
  console.log('3. 测试 API 端点功能');
  
  process.exit(0);
}
